package com.smscenter.server.core.vcomcn;


import com.smscenter.server.core.IQuery;
import com.zeus.base.privilege.utils.ArithUtil;
import com.zeus.base.smscenter.common.constant.SmsConstants;
import com.zeus.base.smscenter.common.constant.VComcnConstants;
import com.zeus.base.smscenter.common.security.MD5;
import com.zeus.base.smscenter.common.util.DateTimeUtils;
import com.zeus.base.smscenter.common.util.WebUtils;
import com.zeus.base.smscenter.common.util.XMLParser;
import com.zeus.base.smscenter.common.util.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ShanFei on 2016-05-27.
 */
public class VComQuery implements IQuery {
	
	public static void main(String[] args) throws Exception {
		Map map = new HashMap();
		map.put("loginName", "fytest1");//即时通fytest1 82557339
		map.put("serviceType", "VOICE");
		map.put("password", MD5.generate("82557339",false).toUpperCase());
		map.put("bizNo", "fygstest20180223155820503");
		VComQuery v = new VComQuery();
        String s = v.querySendRecordInfo(map);
        System.out.println(s);
        //{"state":"成功","duration":"5","phone":"015504607909","tradingNo":"2018020800001","charge":"180"}
	}
	
    @Override
    public String queryBalance(Map<String, Object> params) throws Exception {
        String tenant = params.get("tenant")==null ? "":params.get("tenant").toString();
        String serviceType = params.get("serviceType")==null ? "":params.get("serviceType").toString();
        String data = params.get("data").toString()==null ? "":params.get("data").toString();
        if (StringUtils.isEmpty(tenant)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(serviceType)){
            throw  new Exception("参数:短信类型系统错误:error:短信类型不能为空");
        }
        if(!serviceType.equals("SMS") && !serviceType.equals("VOICE")){
            throw  new Exception("参数:短信类型系统错误:error:短信类型只能为SMS,VOICE");
        }
        String returnMsg = "";
        try {
            StringBuffer paramsStr = new StringBuffer();
            paramsStr.append("<Root Service_Type=\""+(serviceType.equals("SMS") ? "0":"1")+"\">");
            paramsStr.append("<Item>");
            paramsStr.append("<Account_Name>"+tenant+"</Account_Name>");
            paramsStr.append("</Item>");
            paramsStr.append("</Root>");
            returnMsg = WebUtils.doPost(VComcnConstants.SEARCH_URL,paramsStr.toString(), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }

        StringBuffer returnJson = new StringBuffer().append("{");
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Group/Result");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                String accountName = parser.getString(root,"Account_Name");
                String inBalance = parser.getString(root,"InBalance");
                String creditBalance = parser.getString(root,"Credit_Balance");
                String balance = parser.getString(root,"Balance");
                if(!StringUtils.isEmpty(balance)){
                    balance = Double.toString(ArithUtil.div(Double.parseDouble(balance), 1000, 3));
                }
                if (i==0){
                    returnJson.append("\"accountName\"").append(":\"").append(accountName).append("\",");
                    returnJson.append("\"inBalance\"").append(":\"").append(inBalance).append("\",");
                    returnJson.append("\"creditBalance\"").append(":\"").append(creditBalance).append("\",");
                    returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        returnJson.append("}");
        return returnJson.toString();
    }
    
    
    @Override
    public String queryBalanceV2(Map<String, Object> params) throws Exception {
        String tenant = params.get("loginName")==null ? "":params.get("loginName").toString();
        String serviceType = params.get("serviceType")==null ? "SMS":params.get("serviceType").toString();
        if (StringUtils.isEmpty(tenant)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(serviceType)){
            throw  new Exception("参数:短信类型系统错误:error:短信类型不能为空");
        }
        if(!serviceType.equals("SMS") && !serviceType.equals("VOICE")){
            throw  new Exception("参数:短信类型系统错误:error:短信类型只能为SMS,VOICE");
        }
        String returnMsg = "";
        try {
            StringBuffer paramsStr = new StringBuffer();
            paramsStr.append("<Root Service_Type=\""+(serviceType.equals("SMS") ? "0":"1")+"\">");
            paramsStr.append("<Item>");
            paramsStr.append("<Account_Name>"+tenant+"</Account_Name>");
            paramsStr.append("</Item>");
            paramsStr.append("</Root>");
            returnMsg = WebUtils.doPost(VComcnConstants.SEARCH_URL,paramsStr.toString(), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }

        StringBuffer returnJson = new StringBuffer().append("{");
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Group/Result");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
//                String accountName = parser.getString(root,"Account_Name");
//                String inBalance = parser.getString(root,"InBalance");
//                String creditBalance = parser.getString(root,"Credit_Balance");
                String balance = parser.getString(root,"Balance");
                if(!StringUtils.isEmpty(balance)){
                    balance = Double.toString(ArithUtil.div(Double.parseDouble(balance), 1000, 3));
                }
                if (i==0){
                	double unitPrice = 0.0;
                	if ("SMS".equals(params.get("sendType"))) {//如果是查询的文字的取文字价格
                		unitPrice = Double.parseDouble(params.get("unitPrice")+"");
					} else if ("VOICE".equals(params.get("sendType"))) {
						unitPrice = Double.parseDouble(params.get("voiceUnitPrice")+"");
					}
//                    returnJson.append("\"accountName\"").append(":\"").append(accountName).append("\",");
//                    returnJson.append("\"inBalance\"").append(":\"").append(inBalance).append("\",");
//                    returnJson.append("\"creditBalance\"").append(":\"").append(creditBalance).append("\",");
                	
                	returnJson.append("\"money\"").append(":\"").append(balance).append("\",");
                    returnJson.append("\"balance\"").append(":\"").append((int)(Double.parseDouble(balance)/unitPrice)).append("\"");//计算出条数
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        returnJson.append("}");
        return returnJson.toString();
    }

    @Override
    public String queryCollect(Map<String, Object> params) throws Exception {
        String tenant = params.get("tenant")==null ? "":params.get("tenant").toString();
        String password = params.get("password")==null ? "":params.get("password").toString();
        String serviceType = params.get("serviceType")==null ? "":params.get("serviceType").toString();
        String begin = params.get("begin")==null ? "":params.get("begin").toString();
        String end = params.get("end")==null ? "":params.get("end").toString();
        String data = params.get("data").toString()==null ? "":params.get("data").toString();
        if (StringUtils.isEmpty(tenant)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(password)){
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        if (StringUtils.isEmpty(serviceType)){
            throw  new Exception("参数:短信类型系统错误:error:短信类型不能为空");
        }
        if (StringUtils.isEmpty(begin))
            begin = DateTimeUtils.format(new Date(),"yyyy-MM-dd")+" 00:00:00";
        else{
            if(begin.length()!=14){
                throw  new Exception("参数:开始时间系统错误:error:时间格式不正确");
            }
            begin = DateTimeUtils.format(DateTimeUtils.toDate(begin,"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm:ss");
        }
        if (StringUtils.isEmpty(end))
            end =  DateTimeUtils.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
        else{
            if(end.length()!=14){
                throw  new Exception("参数:结束时间系统错误:error:时间格式不正确");
            }
            end =  DateTimeUtils.format(DateTimeUtils.toDate(end,"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm:ss");
        }
        String returnMsg = "";
        try {
            StringBuffer paramsStr = new StringBuffer();
            paramsStr.append("<Root Service_Type=\""+(serviceType.equals("SMS") ? "0":"1")+"\">");
            paramsStr.append("<Item>");
            paramsStr.append("<Account>"+tenant+"</Account>");
            paramsStr.append("<Pwd>"+ MD5.generate(password,false).toUpperCase()+"</Pwd>");
            paramsStr.append("<BTime>"+begin+"</BTime>");
            paramsStr.append("<ETime>"+end+"</ETime>");
            paramsStr.append("<TaskType>"+(serviceType.equals("SMS") ? "0":"1")+"</TaskType>");
            paramsStr.append("</Item>");
            paramsStr.append("</Root>");
            returnMsg = WebUtils.doPost(VComcnConstants.SEARCH_URL,paramsStr.toString(), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }
        StringBuffer returnJson = new StringBuffer().append("{");//返回json串
        try {
            if (returnMsg.equals("01")){
                throw  new Exception("此帐号没有开通服务");
            }
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Result");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                String account = parser.getString(root,"Account");
                String infoType = parser.getString(root,"infoType");
                String btime = parser.getString(root,"Btime");
                String etime = parser.getString(root,"Etime");
                String taskCount = parser.getString(root,"taskCount");
                String charge = parser.getString(root,"charge");
                if (i==0){
                    returnJson.append("\"account\"").append(":\"").append(account).append("\",");
                    returnJson.append("\"infoType\"").append(":\"").append(infoType).append("\",");
                    returnJson.append("\"btime\"").append(":\"").append(btime).append("\",");
                    returnJson.append("\"etime\"").append(":\"").append(etime).append("\",");
                    returnJson.append("\"taskCount\"").append(":\"").append(taskCount).append("\",");
                    returnJson.append("\"charge\"").append(":\"").append(charge).append("\"");
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        returnJson.append("}");
        return returnJson.toString();
    }

	@Override
	public String querySendRecordInfo(Map<String, Object> params) throws Exception {
        String loginName = params.get("loginName")==null ? "":params.get("loginName").toString();
        String password = params.get("password")==null ? "":params.get("password").toString();
        String serviceType = params.get("serviceType")==null ? "":params.get("serviceType").toString();
        String bizNo = params.get("bizNo").toString()==null ? "":params.get("bizNo").toString();
        if (StringUtils.isEmpty(loginName)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(password)){
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        if (StringUtils.isEmpty(serviceType)){
            throw  new Exception("参数:短信类型系统错误:error:短信类型不能为空");
        }
        if (StringUtils.isEmpty(bizNo)){
            throw  new Exception("参数:短信唯一ID系统错误:error:短信唯一ID不能为空");
        }
        String returnMsg = "";
        try {
            StringBuffer paramsStr = new StringBuffer();
            paramsStr.append("<Root Login_Name=\"" + loginName + "\"  Login_Pwd=\"" + password + "\" Service_Type=\""+(serviceType.equals("SMS") ? "0":"1")+"\" InterFaceID=\"0\">");
            paramsStr.append("<Item>");
            paramsStr.append("<Search_ID>"+bizNo+"</Search_ID>");
            paramsStr.append("</Item>");
            paramsStr.append("</Root>");
            System.out.println(paramsStr.toString());
            returnMsg = WebUtils.doPost(VComcnConstants.SEARCH_URL,paramsStr.toString(), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }
        StringBuffer returnJson = new StringBuffer().append("{");//返回json串
        if (returnMsg.equals("01")){
            throw  new Exception("账号或密码错误");
        }
        if (returnMsg.equals("02")){
            throw  new Exception("账号欠费");
        }
        if (returnMsg.equals("10")){
            throw  new Exception("网络或运营商系统内部错误");
        }
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Group/Result");
            for (int i = 0; i < 1 && rootList.getLength() > 0; i++) {
                Node root = rootList.item(i);
                String tradingNo = parser.getString(root,"Search_ID");//唯一ID号  也是我们这边的交易单号
                String phone = parser.getString(root,"Recive_Num");//接收号码
                String duration = parser.getString(root,"Duration");//接听时长(秒)
                String charge = parser.getString(root,"Charge");//花费(厘)
                String state = parser.getString(root,"State");
                if (i==0){
                    returnJson.append("\"state\"").append(":\"").append(state).append("\",");
                    returnJson.append("\"duration\"").append(":\"").append(duration).append("\",");
                    returnJson.append("\"phone\"").append(":\"").append(phone).append("\",");
                    returnJson.append("\"tradingNo\"").append(":\"").append(tradingNo).append("\",");
                    returnJson.append("\"charge\"").append(":\"").append(charge).append("\"");
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        returnJson.append("}");
        return returnJson.toString();
	}

}
